/*
 * @Author       : NaN 353362604@qq.com
 * @Date         : 2023-07-10 17:04:13
 * @LastEditTime : 2023-08-17 15:49:03
 * @LastEditors  : NaN 353362604@qq.com
 * @FilePath     : \AdminStration\src\Common\Modal\ModalList\FlowChart.jsx
 * @Description  :
 */
import '../Scss/FlowChart.scss'
import { Flowchart } from '@ant-design/flowchart'
import { useRequest } from 'ahooks'
import { Http } from '../../Api'
import { useEffect, useState, useRef } from 'react'
import { Timeline, Button, Input, Spin, Select, Result } from 'antd'
import SignatureCanvas from 'react-signature-canvas'

const { TextArea } = Input

const SetUp = {
    toolbarPanelProps: { position: { top: 0, left: 0, right: 0 } },
    scaleToolbarPanelProps: {
        layout: 'horizontal',
        position: { right: 0, top: -40 },
        style: { width: 150, height: 39, left: 'auto', background: 'transparent' },
    },
    canvasProps: { position: { top: 40, left: 0, right: 0, bottom: 0 } },
    nodePanelProps: { position: { width: 160, top: 40, bottom: 0, left: 0 } },
    detailPanelProps: { position: { width: 200, top: 40, bottom: 0, right: 0 } },
}

export const FlowChartModal = () => {
    return (
        <div className="FlowChartModal">
            <Flowchart
                onSave={d => {
                    console.log(d)
                }}
                {...SetUp}
            />
        </div>
    )
}

// 流程表单提交
export const FlowFormSubmitModal = ({ data, Off }) => {
    const signatureRef = useRef()
    const { record, actionRef } = data.data
    const { flowUuid, uuid, isRejectForm, resubmitIsLevelApproval, isSign } = record
    const [loading, setLoading] = useState(false)
    const [Approval, setApproval] = useState(1)
    const { runAsync: posApp } = useRequest(Http, { manual: true })
    const { runAsync: posAttr } = useRequest(Http, { manual: true })
    const { runAsync: posData } = useRequest(Http, {
        manual: true,
        onSuccess: () => {
            actionRef.current.reload()
            Off()
        },
    })

    const submit = () => {
        setLoading(true)
        if (UserList.length !== 0) {
            const data = UserList.map((item, index) => ({
                formUuid: uuid,
                userUuid: item,
                sortId: index + 1,
                flowUuid,
            }))

            posApp({ url: 'posFormAddApprovalFormDetail', data }).then(() => SubmitAnne(flowUuid, uuid))
        } else SubmitAnne(flowUuid, uuid)
    }

    const SubmitAnne = async (flowUuid, uuid) => {
        let path = [flowUuid, uuid, '', Approval]
        if (isSign) {
            const signatureImage = signatureRef.current.toDataURL()
            const res = await posAttr({ url: 'posAttachmentUpdateBase64Image', data: { ImageData: signatureImage } })
            path[2] = res.uuid
        }
        await posData({ url: 'posGenerateApprovalFormDetail', path })
    }

    const [options, setOptions] = useState([])
    const [UserList, setUserList] = useState([])
    const { runAsync: getUser } = useRequest(Http, {
        manual: true,
        onSuccess: res => {
            setOptions(
                res.list.map(({ uuid, tableName, fullName, organizationName }) => ({
                    label: `${organizationName} ${tableName} ${fullName}`,
                    value: uuid,
                })),
            )
        },
    })
    useEffect(() => {
        getUser({ url: 'getUserGroupDetail' })
    }, [getUser])

    const handleClear = () => signatureRef.current.clear()

    return (
        <div className="FlowFormSubmitModal">
            <Result status="warning" title="提交后将不可修改表单明细、表单附件、接受人员等数据" />
            {isRejectForm ? (
                <Select
                    mode="multiple"
                    style={{ width: '100%', marginBottom: 16 }}
                    placeholder="按选择顺序进行审批"
                    onChange={e => setUserList(e)}
                    options={options}
                    filterOption={(input, option) => (option?.label ?? '').includes(input)}
                    filterSort={(optionA, optionB) =>
                        (optionA?.label ?? '').toLowerCase().localeCompare((optionB?.label ?? '').toLowerCase())
                    }
                />
            ) : (
                ''
            )}

            {resubmitIsLevelApproval ? (
                <div className="Approval">
                    <div>是否启用层级审批 : ( {Approval === 0 ? '不启用' : '启用'} )</div>
                    <div>
                        <Button onClick={() => setApproval(0)}>不启用</Button>
                        <Button onClick={() => setApproval(1)} type="primary">
                            启用
                        </Button>
                    </div>
                </div>
            ) : (
                ''
            )}

            {console.log(isSign)}

            {isSign ? (
                <div className="Submit">
                    <div className="Label">请签名</div>
                    <SignatureCanvas
                        ref={signatureRef}
                        penColor="black"
                        canvasProps={{ width: 725, height: 407, className: 'signature' }}
                    />
                    <div className="Button">
                        <Button onClick={handleClear}>重新书写</Button>
                        <Button loading={loading} type="primary" onClick={submit}>
                            {loading ? '提交中...' : '提交审批'}
                        </Button>
                    </div>
                </div>
            ) : (
                <div className="Button">
                    <Button loading={loading} type="primary" onClick={submit}>
                        {loading ? '提交中...' : '提交审批'}
                    </Button>
                </div>
            )}
        </div>
    )
}

// 审批流程
export const FlowChartDetail = ({ data }) => {
    const { uuid } = data.data.record
    const [Items, setItems] = useState([])
    const { runAsync } = useRequest(Http, {
        manual: true,
        onSuccess: res => {
            setItems(
                res.list.map(({ sortId, userName, organizationName, userFullName }) => ({
                    children: (
                        <>
                            <div>第 {sortId} 步</div>
                            <div>
                                {organizationName} {userFullName}
                            </div>
                        </>
                    ),
                })),
            )
        },
    })
    useEffect(() => {
        runAsync({ url: 'getFormGetApprovalFormDetail', data: { formUuid: uuid } })
    }, [runAsync, uuid])
    return <Timeline items={Items} />
}

// 审批记录
export const FlowChartRecords = ({ data }) => {
    const { uuid } = data.data.record
    const [Items, setItems] = useState([])
    const typeList = {
        1: '发起',
        3: '同意',
        4: '不同意',
        99: '下一步',
    }
    const typeColor = {
        1: '#1677ff',
        3: '#52c41a',
        4: '#ff4d4f',
        99: '#faad14',
    }

    const { runAsync } = useRequest(Http, {
        manual: true,
        onSuccess: res => {
            console.log(res)
            setItems(
                res.list.map(
                    ({
                        userName,
                        organizationName,
                        approvalType,
                        approvalDate,
                        approvalStatus,
                        remark,
                        userFullName,
                    }) => ({
                        color: typeColor[approvalStatus],
                        children: (
                            <>
                                <div>
                                    {approvalDate} {typeList[approvalStatus]}
                                </div>
                                <div>
                                    {organizationName} {userFullName}{' '}
                                </div>
                                {remark && <div>原因 : {remark}</div>}
                            </>
                        ),
                    }),
                ),
            )
        },
    })
    useEffect(() => {
        runAsync({ url: 'getFormGetApprovalFormRecords', data: { formUuid: uuid } })
    }, [runAsync, uuid])
    return <Timeline items={Items} />
}

// 审批操作
export const FlowChartApprovalStatus = ({ data, Off }) => {
    const { record, actionRef } = data.data
    const { uuid, isSign } = record
    const signatureRef = useRef()
    const { runAsync: posAttr } = useRequest(Http, { manual: true })
    const { runAsync: posForm } = useRequest(Http, { manual: true })

    const [Status, setStatus] = useState()
    const [loading, setLoading] = useState(false)
    const [remark, setRemark] = useState()

    // posFormUpdateApprovalStatus

    const handleClear = () => signatureRef.current.clear()

    const handleSave = () => {
        setLoading(true)
        const signatureImage = signatureRef.current.toDataURL()
        posAttr({ url: 'posAttachmentUpdateBase64Image', data: { ImageData: signatureImage } }).then(res => {
            const data = { FormUuid: uuid, approvalStatus: 3, userSignatureAttachmentUuid: res.uuid }
            posForm({ url: 'posFormUpdateApprovalStatus', data }).then(() => {
                actionRef.current.reload()
                Off()
            })
        })
    }

    const inputSave = approvalStatus => {
        setLoading(true)
        const data = { FormUuid: uuid, approvalStatus, remark }
        posForm({ url: 'posFormUpdateApprovalStatus', data }).then(() => {
            actionRef.current.reload()
            Off()
        })
    }

    return (
        <div className="FlowChartApprovalStatus">
            <Spin spinning={loading}>
                <Result
                    status="warning"
                    title={isSign ? '同意需签名(签名时请满格签名),不同意需填写原因' : '不同意需填写原因'}
                />
                <div className="Button">
                    <Button
                        type={Status === 3 ? 'primary' : 'default'}
                        onClick={() => {
                            if (isSign) setStatus(3)
                            else inputSave(3)
                        }}
                    >
                        同意
                    </Button>
                    <Button type={Status === 4 ? 'primary' : 'default'} onClick={() => setStatus(4)}>
                        不同意
                    </Button>
                </div>
                {Status === 3 && isSign && (
                    <div>
                        <div className="Label">请签名</div>
                        <SignatureCanvas
                            ref={signatureRef}
                            penColor="black"
                            canvasProps={{ width: 725, height: 407, className: 'signature' }}
                        />
                        <div className="Button">
                            <Button onClick={handleClear}>重新书写</Button>
                            <Button onClick={handleSave}>提交签名</Button>
                        </div>
                    </div>
                )}
                {Status === 4 && (
                    <div>
                        <div className="Label">原因</div>
                        <TextArea
                            value={remark}
                            placeholder="请输入不通过的原因"
                            autoSize={{ minRows: 8 }}
                            onChange={e => setRemark(e.target.value)}
                        />
                        <div className="Button">
                            <Button onClick={() => inputSave(4)}>提交数据</Button>
                        </div>
                    </div>
                )}
            </Spin>
        </div>
    )
}
